package com.wolfking.jeesite.freemarker.method;

import com.wolfking.jeesite.freemarker.FreemarkerMethod;
import com.wolfking.jeesite.sso.SsoConfigService;
import com.wolfking.jeesite.sso.SsoLoginUrlHandler;
import freemarker.template.TemplateMethodModelEx;
import freemarker.template.TemplateModelException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Objects;

@SuppressWarnings("all")
@FreemarkerMethod("getSsoLoginUrl")
public class GetSsoLoginUrlMethod implements TemplateMethodModelEx, InitializingBean {

    @Autowired
    private SsoConfigService ssoConfigService;

    @Autowired(required = false)
    private SsoLoginUrlHandler ssoLoginUrlHandler;

    @Override
    @SuppressWarnings("all")
    public Object exec(List list) throws TemplateModelException {
        String ssoLoginUrl = ssoConfigService.getSsoLoginUrl();
        HttpServletRequest request = ((ServletRequestAttributes)
                RequestContextHolder.getRequestAttributes()).getRequest();
        return ssoLoginUrlHandler.assemblySsoLoginUrl(ssoLoginUrl, request);
    }

    @Override
    public void afterPropertiesSet() {
        if (Objects.isNull(ssoLoginUrlHandler)) {
            ssoLoginUrlHandler = new SsoLoginUrlHandler() {
                @Override
                public String assemblySsoLoginUrl(String ssoLoginUrl, HttpServletRequest request) {
                    if (StringUtils.isNotBlank(ssoLoginUrl)) {
                        return SsoLoginUrlHandler.super.assemblySsoLoginUrl(ssoLoginUrl, request);
                    } else {
                        return "";
                    }
                }
            };
        }
    }
}
